package com.echo.code.thread.mode.eda;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * EventLoop Created by baiyap on 2018/9/24.
 */
public class EventDispatcher implements Router<Event> {

  private final Map<Class<? extends Event>, EventHandler> routerTable;

  public EventDispatcher() {
    this.routerTable = new ConcurrentHashMap<>();
  }

  @Override
  public void registerChannel(Class<? extends Event> eventType, Channel<? extends Event> channel) {
    routerTable.put(eventType, (EventHandler) channel);
  }

  @Override
  public void dispatch(Event event) {
    if (routerTable.containsKey(event.getType())) {
      routerTable.get(event.getType()).dispatch(event);
    }
  }

  public void shutdown() {
    routerTable.values().forEach(EventHandler::stop);
  }
}
